import axios from 'axios'
import session from '@/utils/session'
import responseChain from '@/utils/responseChain'
import constant from '@/utils/constant'
import Vue from "vue";
import qs from 'qs';

let ajax = axios.create({
    baseURL: constant.BaseUrl
});

ajax.interceptors.request.use(config => {
    Vue.prototype.$autoJump();

    let url = config.url;
    if(!url.includes('/sys/relogin')) {
        const accessToken = session.getAccessToken();
        if(accessToken) {
            config.headers['Authorization'] = "Bearer "+accessToken;
        }
    }
    return config;
}, error => {
    return Promise.reject(error);
});

ajax.interceptors.response.use(config => {
    let data = config.data;
    let status = config.status;

    return data;
},err => {
    // 如果handleError为真，则用户需要自己try catch信息
    if(err.response) {
        if(err.response.config.handleError) {
            return Promise.reject(err.response);
        } else {
            return responseChain.statusHandler(err.response);
        }

    } else {
        return  Promise.reject();
    }
});

export default {
    get(url, params={}, handleError=false) {// 显式传入undefined或不传值时使用函数默认参数值；传入''或null时使用传入的参数值。
        return ajax.get(url, {params:params, handleError: handleError});
    },
    post(url, data={}, handleError=false) {
        return ajax.post(url, data, {handleError: handleError});
    },
    postForm(url, data={}, handleError=false) {
        return ajax.post(url, qs.stringify(data), {handleError: handleError});
    },
    put(url, data={}, handleError=false) {
        return ajax.put(url, data, {handleError: handleError});
    },
    delete(url, data={}, handleError=false) {
        return ajax.delete(url, {data: data, handleError: handleError});// {data:}放到方法体，{param:}放到请求url上
    },
    upload(url, data={}, handleError=false) {
        return ajax.post(url, data, { handleError: handleError, headers: {"Content-Type": "multipart/form-data"}});// {data:}放到方法体，{param:}放到请求url上
    },
    upload(url, data={}, handleError=false, uploadProgress) {
        return ajax.post(url, data, { handleError: handleError, headers: {"Content-Type": "multipart/form-data"},onUploadProgress:uploadProgress});// {data:}放到方法体，{param:}放到请求url上
    },
    _axios(config) {
        return ajax(config);
    }
};
